package ro.one.gaeql.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import ro.one.gaeql.common.QueryManager;
import ro.one.gaeql.common.UpdateExecutor;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;

public class GaeQueryManager implements QueryManager {
	@Override
	public UpdateExecutor createUpdateExecutor() {
		return new GaeUpdateExecutor();
	}

	@Override
	public void stopJob(String idJob) { }

	@Override
	public Iterator<String> getJobs() {
		final Iterator<Entity> jobs = JobEntity.getJobs();
		
		return new Iterator<String>() {
			@Override
			public boolean hasNext() { return jobs.hasNext(); }
			@Override
			public String next() { return jobs.next().getKey().getName(); }
			@Override
			public void remove() { }
		};
	}

	@Override
	public String getJobOutput(String idJob) {
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		StringBuilder sb = new StringBuilder(); 

		JobEntity job = JobEntity.get(idJob);
		sb.append(job.getError());
		sb.append("\r\n");
		
		Query q = new Query("Log");
		q.setFilter(new FilterPredicate("idJob", FilterOperator.EQUAL, idJob));
		
		for(Entity entity : ds.prepare(q).asIterable()) {
			Map<String, Object> properties = new HashMap<String, Object>(entity.getProperties());
			properties.remove("idJob");
			sb.append(properties.toString());
			sb.append("\r\n");
		}
		return sb.toString();
	}

	@Override
	public void createTestData() {
		List<Entity> entities = new ArrayList<Entity>();
		
		Random r = new Random();
		
		for (int i = 0; i < 50; i++) {
			Entity customer = new Entity("Customer");
			customer.setProperty("name", "Name " + i);
			customer.setProperty("idDiscount", r.nextInt(3) + 1);
			entities.add(customer);
		}
		
		for (int i = 1; i < 4; i++) {
			Entity discount = new Entity("Discount");
			discount.setProperty("name", "Discount " + i);
			discount.setProperty("idDiscount", i);
			entities.add(discount);
		}
		
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		ds.put(entities);
	}
}
